/****************************************************************************
 *  QLyrics - A simple lyrics viewer.                                       *
 *  Copyright (C) 2008  hsys <hanshuiys@gmail.com>                          *
 *                                                                          *
 *  This program is free software; you can redistribute it and/or modify    *
 *  it under the terms of the GNU General Public License as published by    *
 *  the Free Software Foundation; either version 3 of the License, or       *
 *  (at your option) any later version.                                     *
 *                                                                          *
 *  This program is distributed in the hope that it will be useful,         *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU General Public License for more details.                            *
 *                                                                          *
 *  You should have received a copy of the GNU General Public License       *
 *  along with this program; if not, write to the Free Software Foundation, *
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA       *
 ****************************************************************************/

#include "lyricsprovider.h"

#include <QUrl>
#include <QFileInfo>
#include "configmanager.h"

QString LyricsProvider::getFilename() const {
    QFileInfo info(m_track.url);
    ConfigManager* cfg = ConfigManager::getInstance();
    QString dir = cfg->value("Lyrics/DownloadDirectory", QString("")).toString();
    if (dir.isEmpty())
        dir = info.absolutePath();
    return dir + "/" + info.completeBaseName() + ".lrc";
};

void LyricsProvider::acceptResult(int id) {
    m_file = new QFile(getFilename(), this);
    // if we cannot open local file, just notify and return
    if (!m_file->open(QIODevice::WriteOnly)) {
        m_status = IOError;
        delete m_file;
        emit signalReady();
        return;
    };

    // or we try to download the specified url
    m_http = new QHttp(this);
    QUrl url = QUrl::fromEncoded(m_result[id].url.toAscii());
    QHttp::ConnectionMode mode = url.scheme().toLower() == "https" ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp;
    QHttpRequestHeader header("GET", url.path() + "?" + url.encodedQuery());
    header.setValue("Host", url.host());
    header.setValue("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    header.setValue("Connection", "close");

    m_http->setHost(url.host(), mode, url.port() == -1 ? 80 : url.port());
    if (!url.userName().isEmpty())
        m_http->setUser(url.userName(), url.password());
    connect(m_http, SIGNAL(done(bool)), SLOT(slotDownloadDone(bool)));

    // save the http request id for further use
    m_http->request(header, 0, m_file);
};

void LyricsProvider::cancelResult() {
    m_status = Aborted;
    emit signalReady();
};

QString LyricsProvider::encodeUrlQuery(const QByteArray& url) {
    QString encodedUrl;
    unsigned char c;
    //encode unsafe and gb18030 chars
    for (int i = 0; i < url.size(); i++) {
        c = (unsigned char)url.at(i);
        // hope it works...
        if (c <= 32 || c >= 123 || QByteArray("$+,/:;=?@ \"<>#%\\^[]`").indexOf(c) != -1)
            encodedUrl = encodedUrl + "%" + QString::number(c, 16);
        else
            encodedUrl = encodedUrl + url.at(i);
        /*if (c <= 0x80) {
            if (c <= 32 || c >= 123 || c == '"' || c == '<' || c == '>' || c == '%' || c == '\\' ||
                c == '^' || c == '[' || c == ']' || c == '`' || c == '+' || c == '$' || c == ',')
                encodedUrl = encodedUrl + "%" + QString::number(c, 16);
            else
                encodedUrl = encodedUrl + url.at(i);
        } else {
            //gb18030 2-byte-char and 4-byte-char
            encodedUrl = encodedUrl + "%" + QString::number(c, 16);
            if (i == url.size() - 1) break;
            c = (unsigned char)url.at(++i);
            encodedUrl = encodedUrl + "%" + QString::number(c, 16);
            if (i == url.size() - 1) break;
            if (c >= 0x30 && c <= 0x39) {
                c = (unsigned char)url.at(++i);
                encodedUrl = encodedUrl + "%" + QString::number(c, 16);
                if (i == url.size() - 1) break;
                c = (unsigned char)url.at(++i);
                encodedUrl = encodedUrl + "%" + QString::number(c, 16);
            };
        };*/
    };
    return encodedUrl;
};

void LyricsProvider::slotDownloadDone(bool error) {
    // close the file
    m_file->close();
    if (error || (m_file->error() != QFile::NoError)) {
        m_status = NetworkError;
        m_file->remove();
    } else {
        m_status = Success;
    };
    emit signalReady();
    return;
};

